package com.syqc.monitor.ui.carmonitor

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.base.ChooseTimeViewModel
import com.syqc.entity.DayMile
import com.syqc.entity.HistoryLine
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import com.syqc.utils.DataUtil
import com.syqc.utils.TimeUtil
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.subjects.PublishSubject

/**
 *@Author Jasper
 *@Time   2020/8/8
 *@Desc   選擇车辆
 */
class HistoryLineViewModel : ChooseTimeViewModel() {
    var carId = ""
    var carName = ""
    var teamName = ""

    //上传的参数
    var params = ""

    var videos: String? = null

    //行停行
    var isRunRun = true

    // 停行停
    var isStopStop = true

    private val historyLineSub: PublishSubject<HistoryLine> = PublishSubject.create()
    fun historyLineObserver(): Observable<HistoryLine> = historyLineSub.hide()

    fun getHistory(
        startTime: String,
        endTime: String,
        filter: Boolean,
        maxSpeed: String,
        stopLong: String,
        filterInvalid: Boolean,
        filterAppend: Boolean
    ) {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return
        }
        val speed: String = maxSpeed.ifEmpty { "0" }
        val long = stopLong.ifEmpty { "0" }

        if (isTimeOk(startTime, endTime)) return
        val start = TimeUtil.instance.formatHms(startTime)
        val end = TimeUtil.instance.formatEndHms(endTime)
        toastLoading(true)
        params = "$carId,$start,$end,$filter,$filterInvalid,$filterAppend,$startTime,$endTime"
        ServiceHelper.getRepository().getAllHisGps(
            carId, start, end, speed, long, filterInvalid, filterAppend, filter
        ).autoDispose(this).subscribe(Consumer {
            toastLoading(false)
            if (isHasListData(it.locations, R.string.toast_no_history_line)) return@Consumer
            historyLineSub.onNext(it)
            DataUtil.HistoryLine = it
        }, error)
    }


    private val _mileLive = MutableLiveData<DayMile>()
    val mileLive: LiveData<DayMile> = _mileLive
    fun getDayMile(sTime: String, endTime: String) {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return
        }
        toastLoading(true)
        ServiceHelper.getRepository().getDayMile(carId, sTime, endTime, true).autoDispose(this)
            .subscribe({
                toastLoading(false)
                if (it.list.isNullOrEmpty()) {
                    toast(R.string.toast_no_mile_data)
                    return@subscribe
                }
                _mileLive.postValue(it)
            }, error)
    }
}
